package com.zhr.tea.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * .::::.
 * .::::::::.
 * :::::::::::
 * ..:::::::::::'
 * '::::::::::::'
 * .::::::::::
 * '::::::::::::::..
 * ..::::::::::::.
 * ``::::::::::::::::
 * ::::``:::::::::'        .:::.
 * ::::'   ':::::'       .::::::::.
 * .::::'      ::::     .:::::::'::::.
 * .:::'       :::::  .:::::::::' ':::::.
 * .::'        :::::.:::::::::'      ':::::.
 * .::'         ::::::::::::::'         ``::::.
 * ...:::           ::::::::::::'              ``::.
 * ```` ':.          ':::::::::'                  ::::..
 * '.:::::'                    ':'````..
 * Created by 毛懿 on 2016/11/1 11:45.
 * 邮箱：1334964028@qq.com
 */

public class RetroManager {
    private static volatile RetroManager instance = null;
    private static Retrofit retrofit;
    OkHttpClient client;
    public static final int DEFAULT_TIMEOUT = 15 * 1000;
    private Gson gson;
    String url;


    private RetroManager(String url) {
        this.url = url;
        initOkhttpClient();
        initRetrofit();
    }

    public static RetroManager getInstance(String url) {
        if (instance == null) {
            synchronized (RetroManager.class) {
                if (instance == null) {
                    instance = new RetroManager(url);
                }
            }
        }
        return instance;
    }

    public void initRetrofit() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(client)
                    .baseUrl(url)
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(getGson()))
                    .build();
        }
    }

    private void initOkhttpClient() {
        if (client == null) {
            client = new OkHttpClient.Builder()
                    .readTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                    .build();
        }
    }

    public Gson getGson() {
        return new GsonBuilder()
                .serializeNulls()
                .create();
    }

    public CarService getCarService() {
        return retrofit.create(CarService.class);
    }
}
